<?php
/**
 * description...
 * 
 * @author Administrator
 * @category  
 * @package DnConfig
 */
class DnConfig {
	/** 单例模式 */
	public static function Self($obj = null) {
		$classname = __CLASS__;
		$mustbe_childclass = false;
		$key = 'Dvaknheo_' . $classname;
		if ($obj) {
			if ($mustbe_childclass && !is_a($obj, $classname)) {
				$GLOBALS[$key] = $GLOBALS[$key] ? $GLOBALS[$key] : new $classname ();
			} else {
				$GLOBALS[$key] = $obj;
			}
		} else
			if (!isset ($GLOBALS[$key])) {
				$GLOBALS[$key] = new $classname ();
			}
		return $GLOBALS[$key];
	}
	public function __construct() {
	}
	///////////////////////////////////////////////////////////////////////////
	public static function LoadCsvData($filename, $encode = "GBK") {
		$ret = array ();

		$handle = fopen($filename, "r");
		$keys = fgetcsv($handle, 8192, ",");
		$key_length = sizeof($keys);
		$reserve = fgetcsv($handle, 8192, ",");

		while ($data = fgetcsv($handle, 8192, ",")) {
			if ($x > 100)
				break;
			if (!$data[0])
				continue;

			if ($data[0] == "//END")
				break;
			;
			$line = array ();
			for ($i = 0; $i < $key_length; $i++) {
				if (!$keys[$i]) {
					continue;
				}
				$line[trim($keys[$i])] = iconv($encode, "UTF-8", $data[$i]);
			}
			$ret[] = $line;

		}
		fclose($handle);
		return $ret;
	}
	/**
	 * 这个函数是把 Excel的XML 文件转成 [worksheet][row][cell] 的三维数组
	 */
	protected function LoadExcelXmlInitData($filename) {
		$ret = array ();
		$str = file_get_contents($filename);
		$xml = simplexml_load_string($str);
		$namespaces = $xml->getNamespaces(true);
		foreach ($xml->Worksheet as $worksheet) {
			
			$block_name = '' . $worksheet->attributes($namespaces['ss'])->Name;
			$block_data = array ();

			$rows = $worksheet->Table->Row;
			foreach ($rows as $row) {

				$cells = $row->Cell;

				$line = array ();
				$i = 0;
				foreach ($cells as $cell) {
					$Index = '' . $cell->attributes()->Index;
					if ('' === $Index) {
						$Index = $i;
					}
					$Index = (int) $Index;
					$line[$Index] = '' . $cell->Data;
					if(is_numeric($line[$Index])){
						$line[$Index]=(float)$line[$Index];
					}
					$i++;
				}
				$block_data[] = $line;
			}
			$ret[$block_name] = $block_data;
		}

		return $ret;
	}

	/**
	 * 从 XML 表格 导出所有数据
	 */
	public function LoadExcelXmlData($filename) {
		$configs = $this->LoadExcelXmlInitData($filename);
		$ret = $this->tranAllInitData($configs);
		return $ret;
	}
	/**
	 * 从根据三维数据生成配置文件
	 */
	protected function tranAllInitData($configs) {
		$ret = array ();
		foreach ($configs as $blockname => $block) {
			$ret[$blockname] = $this->tranInitData ($block);
		}
		return $ret;
	}
	protected function dealwithData($data)
	{
		$is_key_value_mode=false;
		
		$title=array();
		foreach($data[0] as $i =>$str){
			if(substr($str,0,2)=='//'){
				continue;
			}
			@list($name,$key)=explode("\n",$str);
			if(!$key)$key=$name;
			$title[$i]=trim($key);
			
		}
		if('key'==$title[0] && 'value'==$title[1]){
			$is_key_value_mode=true;
			
		}
		array_shift($data);
		foreach($data as $row){
			if(!isset($row[0])){continue;}
			if(substr($row[0],0,5)=='//END'){
				break;
			}
			if($is_key_value_mode){
				$ret[$row[0]]=$row[1];
				continue;
			}
			$line=array();
			foreach($row as $i=>$gird){
				if(empty($title[$i])){continue;}
				$line[$title[$i]]=$gird;
			}
			$ret[$row[0]]=$line;
		}
		if($is_key_value_mode){
		}
		return $ret;
	}
	
	protected function tranInitDataLangMode($data) {
	}
	protected function tranInitData($data) {
		$ret = array ();
		$has_key = false;
		$next_ignore = false;
		$keys = array ();
		
		foreach ($data as $row) {
			if ($row[0] == "//END")
				break;
			;
			if (!$row[0])
				continue;
			if ($next_ignore) {
				$next_ignore = false;
				continue;
			}
			if (substr($row[0], 0, 2) == '//') {
				continue;
			}
			if (!$has_key) {
				$keys = array_values($row);
				$has_key = true;
				$next_ignore = true;
				continue;
			}
			$line = array ();
			$key_length = sizeof($keys);

			for ($i = 0; $i < $key_length; $i++) {
				$s = $row[$i];
				if (null == $s) {
					$s = '';
				}
				if (is_numeric($s))
					$s = (int) $s;
				$line[trim($keys[$i])] = $s; //iconv($encode,"UTF-8",$row[$i]);
			}
			$ret[] = $line;
		}
		return $ret;
	}


	public function _lang($str, $paramter = null) {
		global $DN_CONFIGS;
		$DN_CONFIGS=$DN_CONFIGS['Lang_'.'zh_cn'];
		if(!isset($DN_CONFIGS[$str])){
			DnDebug::Log("_lang error: ".$str);
			return $str;
		}
		$str=$Dn_LANG[$str];
		$str=self::LangReplace($str,$paramter = null);
		return $str;
	}
	public function getLanguagesFromFile($file)
	{
		$lang=$this->LoadExcelXmlInitData($file);
		$x=$this->dealwithData($lang['Language']);
		$ret=array();
		foreach($x as $row){
			if(!isset($row['zh_cn'])){continue;}
			$ret[$row['id']]=$row['zh_cn'];
		}
		return $ret;
	}
	////////////////////////////////////////////////////////////
	/**
	 * 获得 $DN_LANG 里的数据
	 */
	public static function Lang($str, $paramter = null) {
		return self::Self()->_lang($str,$paramter);
	}
	public static function LangReplace($str,$paramters = null) {
		if(empty($paramters)){  return $str; }
		foreach($paramters as $key =>$value){
			$key='{'.$key.'}';
			$str=str_replace($key, $value,$str);
		}
		return $str;
	}
	public static function GetLanguageFromBrowser() {
		return 'todo';
		$langs = array ();
		if (isset ($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
			preg_match_all('/([a-z]+(-[a-z]+)?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

			if (count($lang_parse[1])) {
				$langs = array_combine($lang_parse[1], $lang_parse[4]);
				foreach ($langs as $lang => $val) {
					if ($val === '')
						$langs[$lang] = 1;
				}
				arsort($langs, SORT_NUMERIC);
			}
		}
	}
	public function dumpAllConfig()
	{
		global $DN_CONFIGS;
		return $DN_CONFIGS;
	}
	protected function getConfigString($config,$name)
	{
		$str="<"."?php \n"."// generate by ".basename($_SERVER['SCRIPT_FILENAME'])."\n";
		$str.="global \$DN_CONFIGS;\n\$DN_CONFIGS=(is_array(\$DN_CONFIGS))?\$DN_CONFIGS:array();\n";
		$str.="\$DN_CONFIGS['$name']=".var_export($config,true).";\n";
		return $str;
	}
	public function _get($name,$key=null)
	{
		global $DN_CONFIGS;
		if(!isset($DN_CONFIGS[$name])){
			var_dump($name);
		}
		if($key!==null && !isset($DN_CONFIGS[$name][$key])){
			debug_print_backtrace();
			die;
		}
		return (null===$key)?$DN_CONFIGS[$name]:$DN_CONFIGS[$name][$key];
	}
	public static function Get($config,$key=null)
	{
		return self::Self()->_get($config,$key);
	}
}